﻿using Modbus.Device;
using MvCameraControl;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using static Sunny.UI.Net;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace CameraSystem
{
    public partial class Form1 : Form
    {
        [DllImport("TDC_DLL.dll", EntryPoint = "DELTA_DEAL_TEST_DATA_I", CharSet = CharSet.Ansi)]
        public static extern int DELTA_DEAL_TEST_DATA_I(string StrTestType, string TestData, ref StringBuilder pLog_Data);
        static string retTDCInfo;

        bool checkphotoisexist=false;
        private MyCamera m_MyCamera = new MyCamera();
        PixelFormat m_bitmapPixelFormat = PixelFormat.DontCare;
        public static string paraPath=string.Empty;
        public static int CodeLength1 = 0;
        public static int CodeLength2 = 0;
        ModbusTcp PlcModbus = null;
        string codeStr = string.Empty;
        public static bool IsConnected = false;

        readonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice
           | DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;

        ushort d10 = 0;
        ushort d20 = 0;

        string Ip=string.Empty;
        
        ushort d10Loc = 0;
        ushort d20Loc = 0;
        //public bool isCheck=false;
        public List<string> barcodelist = new List<string>();
        public string PhotoWarehouse;
        public int count = 0;
        public string testpath;

        UILabel uiL;
        //Stopwatch stopwatch1 = new Stopwatch();
        //long PlcTime = 0;
        //Stopwatch stopwatch2 = new Stopwatch();
        //long CameraTime2 = 0;

        //Stopwatch stopwatch3 = new Stopwatch();
        //long CameraTime3 = 0;
        public Form1()
        {
            InitializeComponent();

            

            Text = "Auto Check Link MES V1.8";
            uiRichTextBox1.ReadOnly = true;
            uiRichTextBox1.Text = string.Empty;
            toolStripLabel2.Text = "D10-";
            toolStripLabel3.Text = "D20-";
            uiTextBox1.Clear();
            uiDataGridView1.ReadOnly = true;
            paraPath = Application.StartupPath + @"\IniParameters.xml";
            uiTextBox1.Text = string.Empty;
            uiTextBox1.ReadOnly = true;
            uiTextBox1.SelectionStart = 0;

            toolStripButton2.Text = "模拟触发";
            for (int i = 0; i < 10; i++)
            {
                toolStripComboBox1.Items.Add(1000 + 500 * i);
            }
            IniXmlData();
            MaximizeBox = false;
            //WindowState= FormWindowState.Maximized;
            Location = new Point(0, 0);
            Width = Screen.PrimaryScreen.WorkingArea.Width;
        Height =Screen.PrimaryScreen.WorkingArea.Height-5;

            uiL = new UILabel();
            uiL.Location = new Point(0, 0);
            uiL.AutoSize = true;
            uiL.BackColor = Color.Transparent;
            uiL.ForeColor = Color.Red;
            uiL.Font = new Font("Arial", 20F, FontStyle.Bold);
            //uiL.Text = "111";
            pictureBox1.Controls.Add(uiL);

            uiTextBox1.Multiline = false;
            SDKSystem.Initialize();

           // DeviceListAcq();

            CheckForIllegalCrossThreadCalls=false; 
            currentTime=DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(PhotoWarehouse + "\\" + currentTime))
            {
                // 如果路径不存在，则创建它
                Directory.CreateDirectory(PhotoWarehouse + "\\" + currentTime);
            }
            TimePath = PhotoWarehouse + "\\" + currentTime;

            timer2.Enabled = true;

            //string ss = "APPPPPPPPPPPPPPPPPPPPPP" + "\r\n" + "FAIL:THE NEXT GROUP CONTAIN" +" ["+"\""+"PACKING" + "\"" + "]}";
            //StringBuilder sb = new StringBuilder();
            //sb.AppendLine(ss.ToString());
            //toolStripLabel5.Text = sb.ToString().ToLower().Trim();

            //if (toolStripLabel5.Text.Contains("packing"))
            //{
            //    uiTextBox1.Text = "111111";
            //}
            //else { uiTextBox1.Text = "222222"; }


            PlcModbus = new ModbusTcp();


            Thread thread = new Thread(new ThreadStart(ReadPlcThread));//测试
            thread.IsBackground = true;
            thread.Start();


            Thread thread1 = new Thread(new ThreadStart(Listen));//测试
            thread1.IsBackground = true;
            thread1.Start();


            Thread thread2 = new Thread(new ThreadStart(ConnectCameraThread));//测试
            thread2.IsBackground = true;
            thread2.Start();
        }

        private struct MoInfo
        {
            public string retMO;        //馱等
            public string retModel;     //儂笱
            public string retLine;      //盄极
            public string retSection;   //桴梗
            public string retGroup;     //郪梗
            public string retStation;   //桴萸
        };
        bool control = false;
        MoInfo moinfo;
        public void OpenMes()
        {
            //control = false;
            StringBuilder returnStr = new StringBuilder("", 1024);
            try
            {

                int ReturnInteger = DELTA_DEAL_TEST_DATA_I("GET_BASIC_INFO", "N/A}N/A}N/A}N/A}N/A}N/A}", ref returnStr);//馱恁寁馱等
                retTDCInfo = returnStr.ToString().Trim();
                string[] TDCRrturnSplitStr = returnStr.ToString().Trim().Split('}');//枑馱等陓洘

                moinfo.retMO = TDCRrturnSplitStr[0];//馱等
                moinfo.retModel = TDCRrturnSplitStr[1];//儂笱
                moinfo.retLine = TDCRrturnSplitStr[2];//盄极
                moinfo.retSection = TDCRrturnSplitStr[3];//
                moinfo.retGroup = TDCRrturnSplitStr[4];//
                moinfo.retStation = TDCRrturnSplitStr[5];//桴梗
                string tempS = moinfo.retMO.ToString() + "," + "\r\n" + moinfo.retModel.ToString() + "," + "\r\n" + moinfo.retLine.ToString() + "," + "\r\n" + moinfo.retSection.ToString() + "," + "\r\n" + moinfo.retGroup.ToString() + "," + "\r\n" + moinfo.retStation.ToString();
                uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + tempS + "\r\n";

                toolStripLabel5.Text = "机种名：" + moinfo.retModel.ToString() + "      线别：" + moinfo.retLine.ToString() + "      站别：" + moinfo.retStation.ToString();


                control = true;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        int photoNum = 0;
        

        public SerialPort spt = new SerialPort();
        public string cmb_port;
        public string cmb_baud;
        public string cmb_num;
        public string cmb_parity;
        public string cmb_stop;
        string tempBarcode=string.Empty;

        int ScanTime = 0;
        public void Listen()
        {
           while(true) 
            {
                if (control)
                {
                    if (ThreadControl)
                    {

                        if (uiTextBox1.Text.Trim() != "" && uiTextBox1.Text.Trim() != null && uiTextBox1.Text.Trim().Length != 0)
                        {
                            Delay(ScanTime);


                            if (uiTextBox1.Text.Trim().Length == CodeLength1 || uiTextBox1.Text.Trim().Length == CodeLength2)
                            {

                                try
                                {
                                    if (barcodelist.Count > 0)
                                    {
                                        if (uiTextBox1.Text == barcodelist[barcodelist.Count - 1])
                                        {
                                            uiLabel3.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiLabel3.Text = "重复扫码";
                                                uiLabel3.ForeColor = Color.Red;
                                            });
                                            uiTextBox1.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiTextBox1.Clear();
                                            });
                                        }
                                        else
                                        {
                                            tempBarcode = uiTextBox1.Text;
                                            uiTextBox1.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiTextBox1.Clear();
                                            });
                                           

                                          


                                            try
                                            {
                                                StringBuilder returnStr = new StringBuilder(1024);


                                                int rescode = DELTA_DEAL_TEST_DATA_I("ROUTING_UPDATE", tempBarcode + "}" + retTDCInfo + "PASS}PASS}PASS}" + moinfo.retStation + "}PHOTO}NoErr}", ref returnStr);

                                                if (rescode == 0)
                                                {
                                                    uiLabel4.Invoke((MethodInvoker)delegate ()
                                                    {
                                                        uiLabel4.Text = tempBarcode + "\r\n"+ "PASS";
                                                        uiLabel4.BackColor = Color.Lime;



                                                    });

                                                    barcodelist.Add(tempBarcode);

                                                    uiLabel3.Invoke((MethodInvoker)delegate ()
                                                    {
                                                        uiLabel3.Text = "加入队列成功";
                                                        uiLabel3.ForeColor = Color.Green;



                                                    });
                                                    //label1.Text = "pass";
                                                    //label1.BackColor = Color.Green;
                                                }
                                                else
                                                {
                                                    if (returnStr.ToString().ToLower().Trim().Contains("packing"))
                                                    {
                                                        barcodelist.Add(tempBarcode);
                                                        uiLabel3.Invoke((MethodInvoker)delegate ()
                                                        {
                                                            uiLabel3.Text = "加入队列成功";
                                                            uiLabel3.ForeColor = Color.Green;



                                                        });
                                                    }


                                                    uiLabel4.Invoke((MethodInvoker)delegate ()
                                                    {
                                                        uiLabel4.Text = tempBarcode + "\r\n" + returnStr;
                                                        uiLabel4.BackColor = Color.Red;



                                                    });
                                                    //label1.Text = "fail";
                                                    //label1.BackColor = Color.Red;
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                //throw ex;
                                            }

                                            uiDataGridView1.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiDataGridView1.DataSource = null;
                                                uiDataGridView1.DataSource = GetDt();


                                            });


                                            uiTextBox1.Invoke((MethodInvoker)delegate ()
                                            {
                                               
                                                    uiTextBox1.Focus();
                                                
                                            });

                                            tempBarcode = null;
                                        }

                                    }
                                    else
                                    {
                                        tempBarcode = uiTextBox1.Text;
                                        uiTextBox1.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiTextBox1.Clear();
                                        });

                                   

                                        try
                                        {
                                            StringBuilder returnStr = new StringBuilder(1024);


                                            int rescode = DELTA_DEAL_TEST_DATA_I("ROUTING_UPDATE", tempBarcode + "}" + retTDCInfo + "PASS}PASS}PASS}" + moinfo.retStation + "}PHOTO}NoErr}", ref returnStr);

                                            if (rescode == 0)
                                            {
                                                uiLabel4.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiLabel4.Text = tempBarcode + "\r\n" + "PASS";
                                                    uiLabel4.BackColor = Color.Lime;



                                                });
                                                //label1.Text = "pass";
                                                //label1.BackColor = Color.Green;
                                                barcodelist.Add(tempBarcode);

                                                uiLabel3.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiLabel3.Text = "加入队列成功";
                                                    uiLabel3.ForeColor = Color.Green;



                                                });
                                                //label1.Text = "pass";
                                                //label1.BackColor = Color.Green;
                                            }
                                            else
                                            {
                                                if (returnStr.ToString().ToLower().Trim().Contains("packing"))
                                                {
                                                    barcodelist.Add(tempBarcode);

                                                    uiLabel3.Invoke((MethodInvoker)delegate ()
                                                    {
                                                        uiLabel3.Text = "加入队列成功";
                                                        uiLabel3.ForeColor = Color.Green;



                                                    });
                                                }


                                                uiLabel4.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiLabel4.Text = tempBarcode + "\r\n" + returnStr;
                                                    uiLabel4.BackColor = Color.Red;



                                                });
                                                //label1.Text = "fail";
                                                //label1.BackColor = Color.Red;
                                            }

                                        }
                                        catch (Exception ex)
                                        {
                                            //throw ex;
                                        }

                                        uiDataGridView1.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiDataGridView1.DataSource = null;
                                            uiDataGridView1.DataSource = GetDt();


                                        });

                                        uiTextBox1.Invoke((MethodInvoker)delegate ()
                                        {
                                           
                                                uiTextBox1.Focus();
                                          
                                        });

                                        tempBarcode = null;
                                    }
                                }
                                catch { }

                              
                            }


                            else if (uiTextBox1.Text.Trim().Length > CodeLength2)
                            {
                                try
                                {
                                    uiTextBox1.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiTextBox1.Clear();
                                    });

                                    uiLabel3.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiLabel3.Text = "扫码NG-长度大于" + CodeLength2;
                                        uiLabel3.ForeColor = Color.Red;
                                    });
                                }
                                catch { }
                               
                            }

                            else if (uiTextBox1.Text.Trim().Length < CodeLength1)
                            {
                                try
                                {
                                    uiTextBox1.Invoke((MethodInvoker)delegate ()
                                    {

                                        uiTextBox1.Text = string.Empty;
                                        uiTextBox1.SelectionStart = 0;
                                    });


                                    uiLabel3.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiLabel3.Text = "扫码NG-长度小于" + CodeLength1;
                                        uiLabel3.ForeColor = Color.Red;
                                    });
                                }
                                catch { }
                            }

                        }
                      
                    }
                  
                }



                Delay(100); 




            }
        }


        public void ConnectCameraThread()
        {
            while (true)
            {
                if (control)
                {
                    if (IsAutoStart)
                    {
                        IsPhotoSuccess = true;
                        if (deviceInfoList.Count == 0 || cbDeviceList.SelectedIndex == -1)
                        {


                            uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                            {
                                uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "No device, please select!" + "\r\n";
                            });
                            IsAutoStart = false;
                            IsOnce = true;
                            Delay(1000);
                            continue;
                        }

                     

                        try
                        { 
                            // ch:获取选择的设备信息 | en:Get selected device information
                            IDeviceInfo deviceInfo = deviceInfoList[cbDeviceList.SelectedIndex];
                            // ch:打开设备 | en:Open device
                            deviceC = DeviceFactory.CreateDevice(deviceInfo);
                        }
                        catch (Exception ex)
                        {

                            uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                            {
                                uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Create device fail!" + "\r\n";
                            });


                            Delay(1000);
                            continue;
                        }


                        try
                        {
                            int result = deviceC.Open();
                            if (result != MvError.MV_OK)
                            {

                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                {
                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Open device fail!" + "\r\n";
                                });


                                Delay(1000);
                                continue;
                            }


                            //ch: 判断是否为gige设备 | en: Determine whether it is a GigE device
                            if (deviceC is IGigEDevice)
                            {
                                //ch: 转换为gigE设备 | en: Convert to Gige device
                                IGigEDevice gigEDevice = deviceC as IGigEDevice;

                                // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
                                int optionPacketSize;
                                result = gigEDevice.GetOptimalPacketSize(out optionPacketSize);
                                if (result != MvError.MV_OK)
                                {



                                    uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Warning: Get Packet Size failed!" + "\r\n";
                                    });

                                }
                                else
                                {
                                    result = deviceC.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
                                    if (result != MvError.MV_OK)
                                    {
                                        uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Warning: Get Packet Size failed!" + "\r\n";
                                        });
                                    }
                                }
                            }
                        }
                        catch
                        { }



                        try
                        {  
                            // ch:设置采集连续模式 | en:Set Continues Aquisition Mode
                            deviceC.Parameters.SetEnumValueByString("TriggerMode", "On");
                            deviceC.Parameters.SetEnumValueByString("TriggerSource", "Software");
                        }
                        catch { }
                      

                        // ch:获取参数 | en:Get parameters


                        try
                        {
                            // ch:标志位置位true | en:Set position bit true
                            isGrabbing = true;

                            receiveThread = new Thread(ReceiveThreadProcess);
                            receiveThread.IsBackground = true;
                            receiveThread.Start();
                        }
                        catch (Exception ex)
                        {
                            uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                            {
                                uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Start thread failed!" + "\r\n";
                            });

                            throw;
                        }



                        try
                        {
                            int result1 = deviceC.StreamGrabber.StartGrabbing();
                            if (result1 != MvError.MV_OK)
                            {
                                //isGrabbing = false;
                                //receiveThread.Join();

                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                {
                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Start Grabbing Fail!" + "\r\n";
                                });





                                isGrabbing = false;
                                //receiveThread.Join();

                                // ch:停止采集 | en:Stop Grabbing

                                // ch:关闭设备 | en:Close Device
                                if (deviceC != null)
                                {
                                    deviceC.Close();
                                    deviceC.Dispose();
                                }




                                TotalControl = true;
                                IsAutoStart = true;

                                Delay(1000);
                                continue;
                            }
                        }
                        catch { }
                        // ch:开始采集 | en:Start Grabbing
                      


                        //StartToolStripMenuItem.Enabled = false;

                        ThreadControl = true;

                        uiTextBox1.Invoke((MethodInvoker)delegate ()
                        {
                            uiTextBox1.ReadOnly = false;
                            uiTextBox1.Focus();
                        });


                        IsAutoStart = false;


                    }
                }
                Delay(1000);
            }

         
        }


        bool ThreadControl = false;
        bool IsPhotoSuccess = true;
        private void ReadPlcThread()
        {
            while (true)
            {
                if (control)
                {
                    PingReply replyTemp = null;

                    try
                    {
                        replyTemp = PlcModbus.ping.Send(Ip, 500);
                    }
                    catch (Exception ex)
                    {
                        toolStrip1.Invoke((MethodInvoker)delegate () {
                            toolStripLabel1.ForeColor = Color.Red;
                            toolStripLabel1.Text = "PING地址异常";
                        });

                        replyTemp = null;
                    }

                    if (replyTemp != null)
                    {
                        if (replyTemp.Status == IPStatus.Success)
                        {
                            if (IsConnected)
                            {


                                try
                                {
                                    ushort[] tempD10 = PlcModbus.master.ReadHoldingRegisters(1, d10Loc, 1);
                                    d10 = tempD10[0];
                                    ushort[] tempD20 = PlcModbus.master.ReadHoldingRegisters(1, d20Loc, 1);
                                    d20 = tempD20[0];

                                    if (d10 == 0 && count == 0)
                                    {
                                        count = 1;


                                        if (d20 != 0)
                                            PlcModbus.master.WriteSingleRegister(1, d20Loc, 0);
                                    }

                                    if (d10 == 1 && count == 0)
                                    {
                                        count = 1;


                                        if (d20 != 0)
                                            PlcModbus.master.WriteSingleRegister(1, d20Loc, 0);
                                    }

                                    if (d10 == 1 && count == 1)
                                    {
                                        count = 2;

                                        if (barcodelist.Count > 0)
                                        {
                                            IsPhotoSuccess = false;
                                            isPhoto = true;


                                            uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + barcodelist[0] + "  触发成功!" + "\r\n";
                                            });
                                        }

                                        if (d20 != 1)
                                        {
                                            if (IsPhotoSuccess)
                                            {
                                                PlcModbus.master.WriteSingleRegister(1, d20Loc, 1);
                                            }
                                        }
                                    }

                                    if (d10 == 0 && count == 2)
                                    {
                                        count = 0;
                                    }


                                    if (d10 == 1 && count == 2)
                                    {
                                        if (d20 != 1)
                                        {
                                            if (IsPhotoSuccess)
                                            {
                                                PlcModbus.master.WriteSingleRegister(1, d20Loc, 1);
                                            }
                                        }
                                    }



                                    toolStrip1.Invoke((MethodInvoker)delegate ()
                                    {
                                        toolStripLabel2.Text = "D10-" + d10.ToString();
                                    });


                                    toolStrip1.Invoke((MethodInvoker)delegate ()
                                    {
                                        toolStripLabel3.Text = "D20-" + d20.ToString();
                                    });
                                    toolStrip1.Invoke((MethodInvoker)delegate () {
                                        toolStripLabel1.ForeColor = Color.Green;
                                        toolStripLabel1.Text = "数据读取成功";
                                    });

                                }
                                catch
                                {
                                    toolStrip1.Invoke((MethodInvoker)delegate () {
                                        toolStripLabel1.ForeColor = Color.Red;
                                        toolStripLabel1.Text = "数据读取异常";
                                    });

                                    IsConnected = false;
                                }
                            }
                            else
                            {


                                try
                                {
                                    if (PlcModbus.tcpClient != null && PlcModbus.tcpClient.Connected)
                                    {
                                        PlcModbus.tcpClient.GetStream().Close();
                                        PlcModbus.tcpClient.Close();
                                        PlcModbus.tcpClient.Dispose();
                                    }

                                    PlcModbus.tcpClient = new TcpClient(Ip, 502);
                                    PlcModbus.master = ModbusIpMaster.CreateIp(PlcModbus.tcpClient);
                                    PlcModbus.master.Transport.Retries = 0;
                                    PlcModbus.master.Transport.ReadTimeout = 100;
                                    IsConnected = true;
                                }
                                catch
                                {

                                    toolStrip1.Invoke((MethodInvoker)delegate ()
                                    {
                                        toolStripLabel1.ForeColor = Color.Red;
                                        toolStripLabel1.Text = "设备连接异常";
                                    });
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                toolStrip1.Invoke((MethodInvoker)delegate ()
                                {
                                    toolStripLabel1.ForeColor = Color.Red;
                                    toolStripLabel1.Text = "设备连接异常";
                                });

                                if (PlcModbus.tcpClient != null && PlcModbus.tcpClient.Connected)
                                {
                                    PlcModbus.tcpClient.GetStream().Close();
                                    PlcModbus.tcpClient.Close();
                                    PlcModbus.tcpClient.Dispose();
                                }
                            }
                            catch
                            {


                            }
                            finally
                            {
                                IsConnected = false;
                            }

                        }

                    }
                }
             
                
                Delay(50);


              
            }
        }

        #region 毫秒延时
        public void Delay(int mm)
        {
            DateTime current = DateTime.Now;
            while (current.AddMilliseconds(mm) > DateTime.Now)
            {
                try
                {
                    Thread.Sleep(1);//防止CPU
                    Application.DoEvents();
                }
                catch { continue; }

            }
            return;
        }
        #endregion

        public void IniXmlData()
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(paraPath);
                XmlNodeList xmlNode = xmlDocument.SelectSingleNode("IniParameters").ChildNodes;

                foreach (XmlNode item in xmlNode)
                {
                   if (item.Name.ToLower() == "length")
                    {


                        string[] tempL = item.InnerText.Split('-');

                        CodeLength1 = int.Parse(tempL[0]);
                        CodeLength2 = int.Parse(tempL[1]);

                    }
                    if (item.Name.ToLower() == "scantime")
                    {
                        ScanTime = int.Parse(item.InnerText);

                        for (int i = 0; i < toolStripComboBox1.Items.Count; i++)
                        {
                            string tempS = toolStripComboBox1.Items[i].ToString();
                            if (tempS == ScanTime.ToString())
                            {
                                toolStripComboBox1.SelectedIndex = i;
                            }
                        }
                    }
                    if (item.Name.ToLower() == "ip")
                    {
                        Ip = item.InnerText;
                    }
                    if (item.Name.ToLower() == "d10loc")
                    {
                        d10Loc = ushort.Parse(item.InnerText);
                    }
                    if (item.Name.ToLower() == "d20loc")
                    {
                        d20Loc = ushort.Parse(item.InnerText);
                    }
                    if (item.Name.ToLower() == "cmb_port")
                    {
                        cmb_port = item.InnerText;
                    }
                    if (item.Name.ToLower() == "cmb_baud")
                    {
                        cmb_baud = item.InnerText;
                    }
                    if (item.Name.ToLower() == "cmb_num")
                    {
                        cmb_num = item.InnerText;
                    }
                    if (item.Name.ToLower() == "cmb_parity")
                    {
                        cmb_parity = item.InnerText;
                    }
                    if (item.Name.ToLower() == "cmb_stop")
                    {
                        cmb_stop = item.InnerText;
                    }
                    if (item.Name.ToLower() == "warehouse") 
                    {
                        PhotoWarehouse = item.InnerText;
                    }
                    if (item.Name.ToLower()=="testpath") 
                    {
                        testpath = item.InnerText;
                    }

                }

            }
            catch { MessageBox.Show("数据读取异常"); }

        }
    

        public List<IDeviceInfo> deviceInfoList = new List<IDeviceInfo>();
        public IDevice deviceC = null;
      

        bool isGrabbing = false;
        Thread receiveThread = null;

        bool isPhoto = false;
        //bool isRecord = false;
        private readonly object saveImageLock = new object();
        //private IFrameOut frameForSave;  

        bool TotalControl = true;// ch:获取到的帧信息, 用于保存图像 | en:Frame for save image
        public void ReceiveThreadProcess()
        {
            while (isGrabbing)
            {
                if (TotalControl)
                {
                    IFrameOut frameOut;

                    try
                    { 
                        int nRet = deviceC.StreamGrabber.GetImageBuffer(1000, out frameOut);
                        if (MvError.MV_OK == nRet)
                        {
                            try
                            {

                                int result2 = deviceC.Parameters.SetCommandValue("TriggerSoftware");
                                if (result2 != MvError.MV_OK)
                                {
                                    uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Trigger Software Fail!" + "\r\n";
                                    });



                                    isGrabbing = false;
                                    //receiveThread.Join();

                                    // ch:停止采集 | en:Stop Grabbing
                                    deviceC.StreamGrabber.StopGrabbing();

                                    // ch:关闭设备 | en:Close Device
                                    if (deviceC != null)
                                    {
                                        deviceC.Close();
                                        deviceC.Dispose();
                                    }

                                    menuStrip1.Invoke((MethodInvoker)delegate ()
                                    {
                                        StartToolStripMenuItem.Enabled = true;
                                    });

                                    uiTextBox1.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiTextBox1.ReadOnly = true;
                                        uiTextBox1.SelectionStart = 0;
                                    });

                                    TotalControl = true;
                                    IsAutoStart = true;

                                    break;
                                }

                            }
                            catch { }


                            if (isPhoto)
                            {

                               
                                try
                                {
                                    IFrameOut frameForSave = frameOut.Clone() as IFrameOut;


                                    
                                    ImageFormatInfo imageFormatInfo = new ImageFormatInfo();
                                    imageFormatInfo.FormatType = ImageFormatType.Jpeg;
                                    imageFormatInfo.JpegQuality = 90;



                                    int result = SaveImage(imageFormatInfo, frameForSave);
                                    if (result != MvError.MV_OK)
                                    {
                                        try
                                        {
                                            if (barcodelist.Count > 0)
                                            {
                                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + barcodelist[0] + "  拍照异常!" + "\r\n";
                                                });
                                            }
                                            else
                                            {
                                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "  拍照异常!" + "\r\n";
                                                });
                                            }
                                        }
                                        catch { }
                                      



                                    }
                                    else
                                    {



                                        try
                                        {
                                            if (barcodelist.Count > 0)
                                            {
                                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + barcodelist[0] + "  拍照成功!" + "\r\n";
                                                });

                                                uiL.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiL.Text = barcodelist[0];
                                                });

                                                barcodelist.RemoveAt(0);
                                                uiDataGridView1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiDataGridView1.DataSource = null;
                                                    uiDataGridView1.DataSource = GetDt();


                                                });
                                            }
                                            else
                                            {
                                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "  拍照成功!" + "\r\n";
                                                });
                                            }


                                            IsPhotoSuccess = true;
                                            TotalControl = false;
                                        }
                                        catch (Exception e)
                                        {
                                            uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + e.ToString() + "\r\n";
                                            });
                                        }



                                    }


                                }
                                catch (Exception ex)
                                {
                                    uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + ex.ToString() + "\r\n";
                                    });
                                }


                                isPhoto = false;
                            }


                            pictureBox1.Invoke((MethodInvoker)delegate ()
                            {
                                deviceC.ImageRender.DisplayOneFrame(pictureBox1.Handle, frameOut.Image);
                            });


                            try
                            { deviceC.StreamGrabber.FreeImageBuffer(frameOut); }
                            catch { }
                           



                        }
                        else
                        {
                            try
                            {


                                int result2 = deviceC.Parameters.SetCommandValue("TriggerSoftware");
                                if (result2 != MvError.MV_OK)
                                {
                                    uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Trigger Software Fail!" + "\r\n";
                                    });



                                    isGrabbing = false;
                                    //receiveThread.Join();

                                    // ch:停止采集 | en:Stop Grabbing
                                    int result = deviceC.StreamGrabber.StopGrabbing();

                                    // ch:关闭设备 | en:Close Device
                                    if (deviceC != null)
                                    {
                                        deviceC.Close();
                                        deviceC.Dispose();
                                    }

                                    menuStrip1.Invoke((MethodInvoker)delegate ()
                                    {
                                        StartToolStripMenuItem.Enabled = true;

                                    });

                                    uiTextBox1.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiTextBox1.ReadOnly = true;
                                        uiTextBox1.SelectionStart = 0;
                                    });

                                    TotalControl = true;
                                    IsAutoStart = true;

                                    break;
                                }

                            }
                            catch { }


                        }
                    }
                    catch { }
                  

                 



                }
                else
                {
                    if (isPhoto)
                    {
                        try { deviceC.StreamGrabber.ClearImageBuffer(); }
                        catch { }

                        try
                        {
                            IFrameOut frameOut;

                            int nRet = deviceC.StreamGrabber.GetImageBuffer(1000, out frameOut);

                            if (MvError.MV_OK == nRet)
                            {
                                try
                                {

                                    int result2 = deviceC.Parameters.SetCommandValue("TriggerSoftware");
                                    if (result2 != MvError.MV_OK)
                                    {
                                        uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Trigger Software Fail!" + "\r\n";
                                        });



                                        isGrabbing = false;
                                        //receiveThread.Join();

                                        // ch:停止采集 | en:Stop Grabbing
                                        deviceC.StreamGrabber.StopGrabbing();

                                        // ch:关闭设备 | en:Close Device
                                        if (deviceC != null)
                                        {
                                            deviceC.Close();
                                            deviceC.Dispose();
                                        }

                                        menuStrip1.Invoke((MethodInvoker)delegate ()
                                        {
                                            StartToolStripMenuItem.Enabled = true;

                                        });

                                        uiTextBox1.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiTextBox1.ReadOnly = true;
                                            uiTextBox1.SelectionStart = 0;
                                        });

                                        TotalControl = true;
                                        IsAutoStart = true;

                                        break;
                                    }

                                }
                                catch { }




                               
                                try
                                {
                                    IFrameOut frameForSave = frameOut.Clone() as IFrameOut;


                                   
                                    ImageFormatInfo imageFormatInfo = new ImageFormatInfo();
                                    imageFormatInfo.FormatType = ImageFormatType.Jpeg;
                                    imageFormatInfo.JpegQuality = 90;



                                    int result = SaveImage(imageFormatInfo, frameForSave);
                                    if (result != MvError.MV_OK)
                                    {
                                        try
                                        {
                                            if (barcodelist.Count > 0)
                                            {
                                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + barcodelist[0] + "  拍照异常!" + "\r\n";
                                                });
                                            }
                                            else
                                            {
                                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "  拍照异常!" + "\r\n";
                                                });
                                            }
                                        }
                                        catch { }
                                       



                                    }
                                    else
                                    {



                                        try
                                        {
                                            if (barcodelist.Count > 0)
                                            {
                                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + barcodelist[0] + "  拍照成功!" + "\r\n";
                                                });


                                                uiL.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiL.Text = barcodelist[0];
                                                });

                                                barcodelist.RemoveAt(0);
                                                uiDataGridView1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiDataGridView1.DataSource = null;
                                                    uiDataGridView1.DataSource = GetDt();


                                                });
                                            }
                                            else
                                            {
                                                uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                                {
                                                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "  拍照成功!" + "\r\n";
                                                });
                                            }

                                            IsPhotoSuccess = true;
                                        }
                                        catch (Exception e)
                                        {
                                            uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + e.ToString() + "\r\n";
                                            });
                                        }



                                    }


                                }
                                catch (Exception ex)
                                {
                                    uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + ex.ToString() + "\r\n";
                                    });
                                }


                                isPhoto = false;



                                pictureBox1.Invoke((MethodInvoker)delegate ()
                                {
                                    deviceC.ImageRender.DisplayOneFrame(pictureBox1.Handle, frameOut.Image);
                                });


                                try
                                { deviceC.StreamGrabber.FreeImageBuffer(frameOut); }
                                catch { }
                            



                            }
                            else
                            {
                                try
                                {


                                    int result2 = deviceC.Parameters.SetCommandValue("TriggerSoftware");
                                    if (result2 != MvError.MV_OK)
                                    {
                                        uiRichTextBox1.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Trigger Software Fail!" + "\r\n";
                                        });



                                        isGrabbing = false;
                                        //receiveThread.Join();

                                        // ch:停止采集 | en:Stop Grabbing
                                        int result = deviceC.StreamGrabber.StopGrabbing();

                                        // ch:关闭设备 | en:Close Device
                                        if (deviceC != null)
                                        {
                                            deviceC.Close();
                                            deviceC.Dispose();
                                        }

                                        menuStrip1.Invoke((MethodInvoker)delegate ()
                                        {
                                            StartToolStripMenuItem.Enabled = true;

                                        });

                                        uiTextBox1.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiTextBox1.ReadOnly = true;
                                            uiTextBox1.SelectionStart = 0;
                                        });

                                        TotalControl = true;
                                        IsAutoStart = true;

                                        break;
                                    }

                                }
                                catch { }


                            }
                        }
                        catch { }   
                      
                    }
                }







                Delay(50);

            }
        }


        //bool isPhoto=false;
        private int SaveImage(ImageFormatInfo imageFormatInfo,IFrameOut frameForSave)
        {

            if (frameForSave == null)
            {
                throw new Exception("No vaild image");
            }
            string imagePath = string.Empty;

            try
            {
                if (barcodelist.Count > 0)
                {
                    imagePath = TimePath + "\\" + barcodelist[0] + "." + imageFormatInfo.FormatType.ToString();
                }
                else
                {
                    imagePath = testpath + "\\" + "TEST-" + DateTime.Now.ToString("yyMMddhhmmss") + "." + imageFormatInfo.FormatType.ToString();
                }
            }
            catch { }


            try
            { return deviceC.ImageSaver.SaveImageToFile(imagePath, frameForSave.Image, imageFormatInfo, CFAMethod.Equilibrated); }
            catch { return deviceC.ImageSaver.SaveImageToFile(imagePath, frameForSave.Image, imageFormatInfo, CFAMethod.Equilibrated); }
               
           
        }

        bool testB = true;
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    ConnectCamera();
        //}

        private void Form1_Load(object sender, EventArgs e)
        {
            OpenMes();
        }

       

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult res = MessageBox.Show("是否关闭", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)  //1为确定，2为取消,...
            {
                bnClose_Click(sender, e);

                SDKSystem.Finalize();
            }
            if (res == DialogResult.Cancel)  //1为确定，2为取消,...
            {
               e.Cancel = true;
            }


           
        }


        private void bnClose_Click(object sender, EventArgs e)
        {
            // ch:取流标志位清零 | en:Reset flow flag bit
            if (isGrabbing == true)
            {
                bnStopGrab_Click(sender, e);
            }

            // ch:关闭设备 | en:Close Device
            if (deviceC != null)
            {
                deviceC.Close();
                deviceC.Dispose();
            }

            // ch:控件操作 | en:Control Operation
        }


        private void bnStopGrab_Click(object sender, EventArgs e)
        {
            //if (isRecord)
            //{
            //    bnStopRecord_Click(sender, e);
            //}

            // ch:标志位设为false | en:Set flag bit false
            isGrabbing = false;
            //receiveThread.Join();

            // ch:停止采集 | en:Stop Grabbing
            int result = deviceC.StreamGrabber.StopGrabbing();
          

           
        }

        bool IsAutoStart = false;
        private void bnStopRecord_Click(object sender, EventArgs e)
        {
          

            int result = deviceC.VideoRecorder.StopRecord();
          

          
        }

        private void uiRichTextBox1_TextChanged(object sender, EventArgs e)
        {
            uiRichTextBox1.SelectionStart = uiRichTextBox1.Text.Length;
            uiRichTextBox1.ScrollToCaret();
        }

        private void StartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenMes();
           
           // ConnectCamera();

         
        }

        private void StopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            { PlcModbus.master.WriteSingleRegister(1, d20Loc, 1); }
            catch { uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "写入异常" + "\r\n"; }


            uiTextBox1.Focus();

            //barcodelist.Add("1212");

            //uiDataGridView1.DataSource = null;
            //uiDataGridView1.DataSource = GetDt();

        }

        private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start(PhotoWarehouse);
        }

        private void SearchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            barcodelist.Clear();

            uiDataGridView1.DataSource = null;
            uiDataGridView1.DataSource = GetDt();
            //isCheck = false;
            //isPhoto = false;


            //if (isGrabbing == true)
            //{
            //    bnStopGrab_Click(sender, e);
            //}

            //// ch:关闭设备 | en:Close Device
            //if (deviceC != null)
            //{
            //    deviceC.Close();
            //    deviceC.Dispose();
            //}



            //StartToolStripMenuItem.Enabled = true;

            //uiTextBox1.ReadOnly = true;
            //uiTextBox1.SelectionStart = 0;
            //uiTextBox1.Focus();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            { PlcModbus.master.WriteSingleRegister(1, d20Loc, ushort.Parse(toolStripTextBox1.Text)); }
            catch { uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "写入异常" + "\r\n"; }


            uiTextBox1.Focus();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            toolStripLabel4.Text = count+"-"+ TimePath+"-"+IsPhotoSuccess;//isPhoto + "-" +isCheck+"-"+

            DisposeMemory();
           
        }


        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        /// <summary>
        /// 内存释放
        /// </summary>
        private void DisposeMemory()
        {
            try
            {
                GC.Collect();

                GC.WaitForPendingFinalizers();

                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {

                    SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);

                }
            }
            catch { }

        }
        DataTable GetDt()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Column1", typeof(string));

            // 将字符串集合添加到数据表中
            foreach (string str in barcodelist)
            {
                DataRow row = dataTable.NewRow();
                row["Column1"] = str;
                dataTable.Rows.Add(row);
            }

            // 将数据表设置为DataGridView的数据源
            return dataTable;
        }

        private void updateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //UpdateForm up = new UpdateForm(1);
            //up.OnFormDele += Up_OnFormDele;
            //up.ShowDialog();
            try
            { 
                File.WriteAllText(testpath + "\\" + DateTime.Now.ToString("yyMMddhhmmss") + ".txt", uiRichTextBox1.Text);
                MessageBox.Show("LOG导出成功");
            }
            catch { }
           
        }

        private void Up_OnFormDele(int mode, string str)
        {
            try
            {
                if (mode == 1)
                {
                    CodeLength1 = int.Parse(str);


                    ToolClass.UpdateCodeNum(str);

                }
              


                MessageBox.Show("更新成功");
            }
            catch { MessageBox.Show("異常"); }

        }

        bool IsSearch = false;

        private void uiSwitch1_ValueChanged(object sender, bool value)
        {
            if (uiSwitch1.Active)
            {
                uiTextBox1.Clear();
                IsSearch = true;


                //uiTextBox1.Focus();
            }
            else
            {
                uiTextBox1.Clear();
                IsSearch = false;


                //uiTextBox1.Focus();
            }
                
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (barcodelist.Count > 0)
            {
                MessageBox.Show("队列不为空，无法触发");
                return;
            }


            isPhoto = true;



            uiTextBox1.Focus();
        }

        string currentTime = null;
        public string TimePath;
        bool IsOnce = true;
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (IsOnce&&control)
            {
                try
                {
                    IsPhotoSuccess = true;
                    cbDeviceList.Items.Clear();
                    int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList);
                    if (nRet != MvError.MV_OK)
                    {
                        uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "Enumerate devices fail!" + "\r\n";

                        return;

                    }

                    // ch:在窗体列表中显示设备名 | en:Display device name in the form list
                    for (int i = 0; i < deviceInfoList.Count; i++)
                    {
                        IDeviceInfo deviceInfo = deviceInfoList[i];
                        if (deviceInfo.UserDefinedName != "")
                        {
                            cbDeviceList.Items.Add(deviceInfo.TLayerType.ToString() + ": " + deviceInfo.UserDefinedName + " (" + deviceInfo.SerialNumber + ")");
                        }
                        else
                        {
                            cbDeviceList.Items.Add(deviceInfo.TLayerType.ToString() + ": " + deviceInfo.ManufacturerName + " " + deviceInfo.ModelName + " (" + deviceInfo.SerialNumber + ")");
                        }
                    }

                    // ch:选择第一项 | en:Select the first item
                    if (deviceInfoList.Count != 0)
                    {
                        cbDeviceList.SelectedIndex = 0;

                        IsOnce = false;
                        IsAutoStart = true;
                        TotalControl = true;
                    }

                }
                catch { }
             
            }
           


            string temptime = DateTime.Now.ToString("yyyyMMdd");
            if (temptime != currentTime) 
            {
               


                try
                {
                    Directory.CreateDirectory(PhotoWarehouse + "\\" + temptime);
                    currentTime = temptime;
                    TimePath = PhotoWarehouse + "\\" + currentTime;
                    uiRichTextBox1.Text += "[" + DateTime.Now.ToString("yyMMdd hh:mm:ss") + "]" + "：" + "  路径更新成功!" + "\r\n";


                    File.WriteAllText(testpath + "\\" + DateTime.Now.ToString("yyMMddhhmmss") + ".txt", uiRichTextBox1.Text);
                    //MessageBox.Show("LOG导出成功");
                }
                catch { }
            }
        }

        private void toolStripComboBox1_TextChanged(object sender, EventArgs e)
        {
            if (toolStripComboBox1.SelectedItem.ToString() != ScanTime.ToString())
            {
                ScanTime = int.Parse(toolStripComboBox1.SelectedItem.ToString());


                ToolClass.UpdateCodeNum(toolStripComboBox1.SelectedItem.ToString());
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            try
            {
               
                    uiTextBox1.Focus();
               
            }
            catch { }
           
        }
        //protected override void WndProc(ref Message m)
        //{
        //    try
        //    {
        //        if (m.Msg == 0x112)
        //        {
        //            switch ((int)m.WParam)
        //            {
        //                //禁止拖拽标题栏还原窗体
        //                case 0xF012:
        //                case 0xF010:
        //                    m.WParam = IntPtr.Zero;
        //                    break;
        //                ////禁止双击标题栏
        //                //case 0xf122:
        //                //    m.WParam = IntPtr.Zero;
        //                //    break;
        //            }
        //        }
        //        base.WndProc(ref m);
        //    }
        //    catch { }
        //}
    }
   
}
